/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.visitorAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.DetermineLogin;
import com.mxg.blog.common.ResultCode;
import com.mxg.blog.common.UserOperate;
import com.mxg.blog.entity.Message;
import com.mxg.blog.service.MessageService;
import com.mxg.blog.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/7/28 2:26
 * 获取message信息, 初版, 暂没有开放访客注册和登录, 消息使用ip地址做为唯一识别
 */
@RestController
@RequestMapping("/api")
public class MessageAdmin {
    CqLogger cqLogger = CqLogger.getInstance();

    private final UserService userService;
    private final MessageService messageService;
    public MessageAdmin(MessageService messageService, UserService userService)
    {
        this.messageService = messageService;
        this.userService = userService;
    }

    @PostMapping("/getMessages")
    public ResponseEntity<Map<String, Object>> getMessages(@RequestBody Map<String, String> requestMap){
        Map<String, Object> resultMap = new HashMap<>();

        cqLogger.print(requestMap);

        DetermineLogin determineLogin = DetermineLogin.getInstance(requestMap.get("userAccount"), userService);

        if(determineLogin.startJudge().equals(DetermineLogin.NOT_LOGIN)){
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_NOT_LOGIN);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_NOT_LOGIN);
        }else {
            List<Map<String, Object>> tableData = new ArrayList<>();
            List<Message> messageList = messageService.getMessages();

            for (Message message : messageList) {
                Map<String, Object> messageInfo = new HashMap<>();
                messageInfo.put(ResultCode.ip, message.getMessageIp());
                messageInfo.put(ResultCode.name, message.getMessageName());
                messageInfo.put(ResultCode.phone, message.getMessagePhone());
                messageInfo.put(ResultCode.email, message.getMessageEmail());
                messageInfo.put(ResultCode.content, message.getMessageConnect());
                tableData.add(messageInfo);
            }

            resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
            resultMap.put(ResultCode.tableData, tableData);
            resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);
        }
        return ResponseEntity.ok(resultMap);
    }

}
